import dash
from app.base_html_string import base_html_string
from flask_login import login_required


def register_dash_app(app):
    from app.dashapp.layout import layout
    from app.dashapp.callbacks import register_callbacks

    # Meta tags for viewport responsiveness
    meta_viewport = {"name": "viewport", "content": "width=device-width, initial-scale=1, shrink-to-fit=no"}

    dash_app = dash.Dash(__name__,
                         server=app,
                         url_base_pathname='/dash/',
                         meta_tags=[meta_viewport],
                         index_string=base_html_string
    )

    with app.app_context():
        dash_app.title = 'Dash Example'
        dash_app.layout = layout
        register_callbacks(dash_app)

    _protect_dash_views(dash_app)


def _protect_dash_views(dash_app):
    for view_func in dash_app.server.view_functions:
        if view_func.startswith(dash_app.config.url_base_pathname):
            dash_app.server.view_functions[view_func] = login_required(dash_app.server.view_functions[view_func])
